package com.xk857.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xk857.article.mapper.CommentMapper;
import com.xk857.article.service.ICommentService;
import com.xk857.entities.Comment;
import com.xk857.util.base.Result;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 评论信息表 服务实现类
 *
 * @author CV大魔王
 * @since 2021-02-21
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Override
    public List<Comment> findByArticleId(String articleId) {
        if (StringUtils.isBlank(articleId)) {
            return null;
        }
        return baseMapper.findByArticleId(articleId);
    }

    @Override
    public Result deleteById(String id) {
        if (StringUtils.isBlank(id)) {
            return Result.error("评论ID不能为空");
        }
        // 要删除的所有评论id
        ArrayList<String> ids = new ArrayList<>();
        //先把要删除的一级评论id放入到集合中
        ids.add(id);
        //递归的子评论 id 加入到集合中
        this.getIds(ids, id);
        //批量删除集合中的id
        baseMapper.deleteBatchIds(ids);
        return Result.ok();
    }

    @Override
    public Integer searchCountDayNum() {
        return baseMapper.searchCountDayNum();
    }

    @Override
    public Integer searchNumberOfArticlesInYesterdaySDay() {
        return baseMapper.searchNumberOfArticlesInYesterdaySDay();
    }

    @Override
    public Integer searchNumberOfArticlesInWeek() {
        return baseMapper.searchNumberOfArticlesInWeek();
    }

    /**
     * 递归方法
     * @param ids 要删除的所有评论id
     * @param parentId 父评论id
     */
    private void getIds(List<String> ids, String parentId) {
        //查询子评论的对象
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        List<Comment> commentList = baseMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(commentList)) {
            for (Comment comment : commentList) {
                String id = comment.getId();
                ids.add(id);
                // 递归继续查询子评论id
                this.getIds(ids, id);
            }
        }
    }
}
